<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="标题" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />&nbsp;
      <el-select v-model="listQuery.level" placeholder="关键词等级" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in keywordCountOptions" :key="item" :label="item" :value="item" />
      </el-select>&nbsp;
      <el-select v-model="listQuery.type" placeholder="类型" clearable class="filter-item" style="width: 150px">
         <el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>&nbsp;
      <el-select v-model="listQuery.sort" style="width: 150px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>&nbsp;
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <!-- 广告ID -->
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="auto" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <!-- 广告标题 -->
      <el-table-column label="标题" min-width="auto">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
        </template>
      </el-table-column>

      <!-- 广告主 -->
      <el-table-column label="广告商家" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.publishName }}</span>
        </template>
      </el-table-column>

      <!-- 广告类型 -->
      <el-table-column label="类型" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.type }}</span>
        </template>
      </el-table-column>

      <!-- 关键词数量 -->
      <el-table-column label="关键词等级" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.level }}</span>
        </template>
      </el-table-column>

      <!-- 点击次数 -->
      <el-table-column label="点击次数" align="center" width="auto">
        <template slot-scope="{row}">
          <span>{{ row.clickNumber }}</span>
        </template>
      </el-table-column>

      <!-- 基础广告费 -->
      <el-table-column label="基本费用" align="center" width="auto">
        <template slot-scope="{row}">
          <span>{{ row.basePrice }}</span>
        </template>
      </el-table-column>

      <!-- 总广告费 -->
      <el-table-column label="总费用" align="center" width="auto">
        <template slot-scope="{row}">
          <span>{{ row.totalPrice }} </span>
        </template>
      </el-table-column>

      <!-- 广告图片 -->
      <el-table-column label="图片" align="center" width="auto">
        <template slot-scope="{row}">
          <span>{{ row.image }}</span>
        </template>
      </el-table-column>

      <!-- 操作者 -->
      <el-table-column label="操作者" align="center" width="auto">
        <template slot-scope="{row}">
          <span>{{ row.operator }}</span>
        </template>
      </el-table-column>

       <!-- 操作日期 -->
       <el-table-column label="操作日期" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <!-- 广告状态 -->
      <el-table-column label="状态" class-name="status-col" width="auto" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <!-- <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            发布
          </el-button>
          <el-button v-if="row.status!='draft'" size="mini">
            已发布
          </el-button> -->
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getAdList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
       
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>

        <el-form-item label="广告类型" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
            <el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name" :value="item.display_name" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="基本费用" prop="point">
          <el-select v-model="temp.basePrice" class="filter-item" placeholder="Please select">
            <el-option v-for="item in basepriceOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="关键词等级">
          <el-select v-model="temp.keywordCount" class="filter-item" placeholder="Please select">
            <el-option v-for="item in keywordCountOptions" :key="item" :label="item" :value="item " />
          </el-select>
        </el-form-item>
            
        <el-form-item label="具体描述">
          <el-input v-model="temp.content" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createAdData():updateAdData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchAdList, createAd, updateAd } from '@/api/ad'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import Upload from '@/components/Upload/SingleImage'


const typeOptions = [
  { key: 'Sport', display_name: '健身' },
  { key: 'Food', display_name: '美食' },
  { key: 'Play', display_name: '游玩' },
  { key: 'Traffic', display_name: '交通' },
  { key: 'Study', display_name: '学习' },
  { key: 'Daily', display_name: '日用品' }
]

const typeKeyValue = typeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.type_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination, Upload },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        // draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      // inputValue:'',
      listQuery: {
        page: 1,
        limit: 20,
        // sort: '+id',
      },
      keywordCountOptions:[1,2,3,4,5],
      typeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      // statusOptions: ['published', 'draft', 'deleted'],
      statusOptions: ['published', 'deleted'],
      basepriceOptions: [500,800,1200],
      temp: {
        id: undefined,
        keywordCount: '',
        basePrice:'',
        clickNumber:'',
        content: '',
        timestamp: new Date(),
        title: '',
        type: '',
        // tag:'',
        status: 'published',
        image:''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      rules: {
        keywordCount: [{ required: true, message: 'keywordCount is required', trigger: 'change' }],
        basePrice: [{ required: true, message: 'baseprice is required', trigger: 'change' }],
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  computed:{
    totalPrice: {
      get() {
        return (this.baseprice + 5*this.clickNumber)
      }
    },
  },
  created() {
    this.getAdList()
  },
  methods: {
    // 获取任务列表
    getAdList() {
      this.listLoading = true
      fetchAdList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total

        // 模拟请求时间
        setTimeout(() => {this.listLoading = false}, 1.5 * 1000)
      })
    },

    // 处理筛选操作
    handleFilter() {
      this.listQuery.page = 1
      this.getAdList()
    },

    // 处理状态转换
    // handleModifyStatus(row, status) {
    //   this.$message({
    //     message: '操作成功',
    //     type: 'success'
    //   })
    //   row.status = status
    // },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },

    // 重置 temp 对象的属性为默认值，以便在需要时重新初始化该对象
    resetTemp() {
      this.temp = {
        id: undefined,
        keywordCount: '',
        basePrice: '',
        clickNumber:'',
        totalPrice:'',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },

    // 处理创建任务数据
    // 重置temp对象——设置对话框状态为创建——显示对话框——清除表单验证
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 创建任务数据
    createAdData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // 随机ID
          this.temp.author = '新苗管理员'
          createAd(this.temp).then(() => {
            this.list.unshift(this.temp) //表头插入
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleUpdate(row) {
      this.temp = Object.assign({}, row) // 复制传入的行数据到 temp 对象
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateAdData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp)
          updateAd(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp) //替换列表中相应ID的任务数据
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', 'title', 'type', 'keywordCount','clickNumber','basePrice','totalPrice','operator','operateTime', 'status']
        const filterVal = ['id', 'title', 'type', 'keywordCount','clickNumber','basePrice','totalPrice','operator','operateTime', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>